package com.jvup.gameshow.utils;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.widget.Toast;

import com.jvup.gameshow.model.entity.ImageFloder;
import com.jvup.gameshow.model.entity.ImageItem;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author LYF
 * @time 2017/10/27 0027 12:32
 * desc:帮助查询图片
 * use:
 */

public class ContentResolverUtils {

    public static void queryImages(Context context, ImageFloder imageAll, ArrayList<ImageFloder> mDirPaths){
        Cursor mCursor = null;
        try {
            mCursor = context.getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[] { MediaStore.Images.ImageColumns.DATA }, "",
                    null, MediaStore.MediaColumns.DATE_ADDED + " DESC");
            HashMap<String, Integer> tmpDir = new HashMap<>();
            if (mCursor.moveToFirst()) {
                int _date = mCursor.getColumnIndex(MediaStore.Images.Media.DATA);
                do {
                    // 获取图片的路径
                    String path = mCursor.getString(_date);
                    // Log.e("TAG", path);
                    imageAll.images.add(new ImageItem(path));
                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null) {
                        continue;
                    }
                    ImageFloder imageFloder = null;
                    String dirPath = parentFile.getAbsolutePath();
                    if (!tmpDir.containsKey(dirPath)) {
                        // 初始化imageFloder
                        imageFloder = new ImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                        mDirPaths.add(imageFloder);
                        tmpDir.put(dirPath, mDirPaths.indexOf(imageFloder));
                    } else {
                        imageFloder = mDirPaths.get(tmpDir.get(dirPath));
                    }
                    imageFloder.images.add(new ImageItem(path));
                } while (mCursor.moveToNext());
            }
        } catch (Exception e) {
            Toast.makeText(context, "请检查权限", Toast.LENGTH_SHORT).show();
        } finally {
            if (mCursor != null) {
                mCursor.close();
            }
        }
    }


}
